# -*- coding: utf-8 -*-
"""
analyze_method_summary.py
读取原始 analysis_aggregate.csv（或 26a28fd0-bad6-4441-bee8-6b87898e09d8.csv）
重新分类 Hybrid / IBVS / PBVS，
生成：
 - method_summary.csv
 - triple_axis_summary.png（总体三轴）
 - two_axis_summary.png（总体双轴）
 - triple_axis_1011_hy.png / pb.png / pv.png （10.11静态子集）

图表特性：
  * 左轴：误差中位数（mm，柱状）
  * 右轴（内侧）：成功率（%，折线）
  * 右轴（外侧偏移）：平均误差（mm，折线/方形散点）
  * 双轴图仅显示左（误差）+右（成功率）
"""

import os, re
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

# ---------- 加载原始数据 ----------
SRC = "all_analysis.csv"
df = pd.read_csv(SRC)

# ---------- 分类：方法 + 动静态 ----------
methods, conditions = [], []
for path in df["dir_name"]:
    lower = path.lower()
    # 动态/静态判别
    if "1010" in lower:
        condition = "dynamic"
    elif "1011" in lower:
        condition = "static"
    else:
        condition = "static"
    conditions.append(condition)

    # 方法分类
    parts = re.split(r"[\\/]", lower)
    basename = parts[-1]
    if basename.startswith("hy"):
        method = "Hybrid"
    elif basename.startswith("pb"):
        method = "IBVS"     # 10.11/pb*
    elif basename.startswith("pv"):
        method = "PBVS"     # 10.11/pv*
    elif "10.09" in lower:
        method = "PBVS"
    elif "10.10" in lower:
        method = "IBVS"
    else:
        method = "PBVS"
    methods.append(method)

df["method"] = methods
df["condition"] = conditions

# ---------- 数据类型转换 ----------
df["converged_bool"] = df["converged"].astype(str).str.upper().str.contains("YES|TRUE|1")
df["final_error_norm_num"] = pd.to_numeric(df["final_error_norm"], errors="coerce")

# ---------- 汇总统计 ----------
def summarize(data):
    g = data.groupby("method", dropna=False)
    out = g.agg(
        sample_count=("method", "size"),
        success_count=("converged_bool", lambda s: np.nansum(s.astype(float))),
        success_rate=("converged_bool", lambda s: np.nanmean(s.astype(float))*100),
        final_error_norm_median=("final_error_norm_num", "median"),
        final_error_norm_mean=("final_error_norm_num", "mean"),
        final_error_norm_std=("final_error_norm_num", "std"),
    ).reset_index()
    return out

summary = summarize(df)
summary.to_csv("method_summary.csv", index=False)

print("=== Summary ===")
print(summary)

# ---------- 绘图函数 ----------
def plot_triple_axis(summary_df, title, out_path):
    methods = summary_df["method"].tolist()
    x = np.arange(len(methods))
    med = summary_df["final_error_norm_median"].values
    mean = summary_df["final_error_norm_mean"].values
    sr = summary_df["success_rate"].values

    fig, ax1 = plt.subplots(figsize=(8,5), dpi=150)

    ax1.bar(x, med, width=0.6, label="Median Error (mm)")
    ax1.set_ylabel("Median Error (mm)")
    ax1.set_xlabel("Method")
    ax1.set_xticks(x)
    ax1.set_xticklabels(methods, rotation=10)

    ax2 = ax1.twinx()
    ax2.plot(x, sr, marker="o", label="Success Rate (%)")
    ax2.set_ylabel("Success Rate (%)")
    ax2.set_ylim(0,100)

    ax3 = ax1.twinx()
    ax3.spines["right"].set_position(("axes",1.12))
    ax3.set_frame_on(True)
    ax3.patch.set_visible(False)
    for sp in ax3.spines.values(): sp.set_visible(True)
    ax3.plot(x, mean, marker="s", linestyle="--", label="Mean Error (mm)")
    ax3.set_ylabel("Mean Error (mm)")

    plt.title(title)
    plt.tight_layout()
    plt.savefig(out_path)
    plt.close(fig)

def plot_two_axis(summary_df, title, out_path):
    methods = summary_df["method"].tolist()
    x = np.arange(len(methods))
    med = summary_df["final_error_norm_median"].values
    mean = summary_df["final_error_norm_mean"].values
    sr = summary_df["success_rate"].values

    fig, ax1 = plt.subplots(figsize=(8,5), dpi=150)
    ax1.bar(x, med, width=0.6, label="Median Error (mm)")
    ax1.plot(x, mean, marker="s", linestyle="--", label="Mean Error (mm)")
    ax1.set_ylabel("Final Error (mm)")
    ax1.set_xlabel("Method")
    ax1.set_xticks(x)
    ax1.set_xticklabels(methods, rotation=10)

    ax2 = ax1.twinx()
    ax2.plot(x, sr, marker="o", label="Success Rate (%)")
    ax2.set_ylabel("Success Rate (%)")
    ax2.set_ylim(0,100)

    h1,l1=ax1.get_legend_handles_labels()
    h2,l2=ax2.get_legend_handles_labels()
    ax1.legend(h1+h2,l1+l2,loc="best")
    plt.title(title)
    plt.tight_layout()
    plt.savefig(out_path)
    plt.close(fig)

# ---------- 绘制总体图 ----------
plot_triple_axis(summary, "Summary: Median Error, Success Rate, Positioning Accuracy",
                 "triple_axis_summary.png")
plot_two_axis(summary, "Summary (Two-Axis): Error & Success Rate",
              "two_axis_summary.png")

# ---------- 绘制 10.11 子集 ----------
df_1011 = df[df["dir_name"].str.contains("1011", case=False, regex=False)]
for key, label in {"hy":"Hybrid","pb":"IBVS","pv":"PBVS"}.items():
    sub = df_1011[df_1011["method"]==label]
    if not sub.empty:
        sm = summarize(sub)
        plot_triple_axis(sm, f"10.11 {label}: Median Error, Success Rate, Positioning Accuracy",
                         f"triple_axis_1011_{key}.png")

print("图与表生成完成。")
